var ctx;
var cellId;
var regionId;
var buildingId ;
var unitId ;
var houseId 

var area;
var unitPrice;
var month;
var rate;
var money;
var beginDate;
var endDate;
var billType;
var billTitle;

var fileIds;
var filePath;

function setCtx(ctx) {
	this.ctx = ctx;
}

//判断是否为空
function ifNull(mess){
	if(mess == null || mess == undefined){
		mess = "";
	}
	return mess;
}

//验证标题
function checkDate(){
	var beginDate = $("#beginDate").val();
	if(beginDate == null || beginDate == ""){
		layer.tips('开始时间不能为空!', '#beginDate', {
		    tips: 3
		});
		return false;
	}else{
		return true;
	}
}

//验证标题
function checkCell(){
	var cellId = $("#cellId").val();
	if(cellId == null || cellId == ""){
		layer.tips('小区名不能为空!', '#cellId', {
		    tips: 3
		});
		return false;
	}else{
		return true;
	}
}

//验证月数
function checkMonth(){
	month = $('#month').val();
	//解决ie9以下placeholder与value重复的问题
	if(month == $("#month").attr("placeholder")){
		month = "";
	}
	if(month == null || month == "" || month< 1 || month >24){
		layer.tips('月数请输入1-24 ！', '#month', {
		    tips: 3
		});
		return false;
	}else{
		return true;
	}
}

//点击小区、楼栋等级联选择
function changeAddr (obj,num) {
	if (num ==1) {
		var id = $("#cellId").val();
	}
	if (num ==2) {
		var id = $("#regionId").val();
	}
	if (num ==3) {
		var id = $("#buildingId").val();
	}
	if (num ==4) {
		var id = $("#unitId").val();
	}
	if (id != ''){
		$.ajax({
	        type : "GET",
	        url : ctx + "/feeBill/changeAddr",
	        cache : false,
	        dataType : 'json',
	        data : {
	        	id : id,
	        	num:num
	        },
	        success : function(data) {
	        	if (data.success) {
	        		if (num == 1) {
	        			var result = "<option value='" + "'>区域</option>";
	                    $.each(data.obj, function(index, item) {
	                        result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
	                    });
	                    $("#regionId").html('');
	                    $("#regionId").append(result);
	                    $("#regionId").change();
	        		}
	        		if (num == 2) {
	        			var result = "<option value='" + "'>楼栋</option>";
	                    $.each(data.obj, function(index, item) {
	                        result += "<option id='" + item.buildingName + "'" + " value='" + item.id + "'>" + item.buildingName + "</option>";
	                    });
	                    $("#buildingId").html('');
	                    $("#buildingId").append(result);
	                    $("#buildingId").change();
	        		}
	        		if (num == 3) {
	        			var result = "<option value='" + "'>单元</option>";
	                    $.each(data.obj, function(index, item) {
	                        result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
	                    });
	                    $("#unitId").html('');
	                    $("#unitId").append(result);
	                    $("#unitId").change();
	        		}
	        		if (num == 4) {
	        			var result = "<option value='" + "'>房间号</option>";
	                    $.each(data.obj, function(index, item) {
	                        result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
	                    });
	                    $("#houseId").html('');
	                    $("#houseId").append(result);
	                    $("#houseId").change();
	        		}
	            }
	        }
		});
	} else {
		if (num == 1) {
			var result = "<option value='" + "'>区域</option>";
			$("#regionId").html('');
            $("#regionId").append(result);
            $("#regionId").change();
		}
		if (num == 2) {
			var result = "<option value='" + "'>楼栋</option>";
			$("#buildingId").html('');
            $("#buildingId").append(result);
            $("#buildingId").change();
		}
		if (num == 3) {
			var result = "<option value='" + "'>单元</option>";
			$("#unitId").html('');
            $("#unitId").append(result);
            $("#unitId").change();
		}
		if (num == 4) {
			var result = "<option value='" + "'>区域</option>";
			$("#houseId").html('');
            $("#houseId").append(result);
            $("#houseId").change();
		}
	}
	
	
		
}

var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
//保存或新增方法
function initList() {
	var cellId = ifNull($("#cellId").val());
	var regionId = ifNull($("#regionId").val());
	var buildingId = ifNull($("#buildingId").val());
	var unitId = ifNull($("#unitId").val());
	var houseId = ifNull($("#houseId").val());
	var beginDate = ifNull($("#beginDate").val());;
	
	if(checkDate() && checkCell()){
		$.ajax({
			type : "POST",
			url : ctx + "/feeBill/initBillList",
			cache : false,
			dataType : 'json',
			data: {
				cellId : cellId,
				regionId : regionId,
				buildingId : buildingId,
				unitId : unitId,
				houseId : houseId,
				beginDate : beginDate
			},
			success : function(result) {
				if (result.success) {
					layer.msg(result.msg,{
						icon: 1,
						time: 3000 //2秒关闭（如果不配置，默认是3秒）
					},function(){
						parent.loadContent("/feeBill/infoList");
						parent.layer.close(index);
					});
				} else {
					layer.msg("操作失败",{
						icon: 2
					});
				}
			}
		});
	}
}

//返回上一页
function cancel(){
	loadContent("/feeBill/infoList");
}

//输入月数，自动计算总金额
function showMoney () {
	area= $('#area').val();
	unitPrice= $('#unitPrice').val();
	rate= $('#rate').val();
	month = $('#month').val();
	money = (area*unitPrice*rate*month).toFixed(2);
	$('#money').val(money);
	
	beginDate = $('#beginDate').val();
	endDate = getAfterMonth (beginDate,month);
	$('#endDate').val(endDate);
}

//选择发票
function changeType() {
	var num = $('#billType').val();
	if (num == 1 || num == 2) {
		$('#isTitle').show();
	} else {
		$('#isTitle').hide();
	}
}

function getAfterMonth (beginDate,mon) {
	var s = beginDate.split("-"); 
    var yy = parseInt(s[0]); 
    var mm = parseInt(s[1])-1 ;  
    var dd = parseInt(s[2]);  
    var dt = new Date(yy, mm, dd);  
    var n= parseInt(mon);
    
    dt.setDate(dt.getDate() -1);
    
    dt.setMonth(dt.getMonth() + n);
    var month = parseInt(dt.getMonth()) + 1;
    
    if ((dt.getYear() * 12 + dt.getMonth()) > (yy * 12 + mm + n)) {
        dt = new Date(dt.getYear(), dt.getMonth(), 0); 
    }
    
    return dt.getFullYear() + "-" + month  + "-" + dt.getDate(); 
}


function saveBill () {
	month = $('#month').val();
	money = $('#money').val();
	beginDate= $('#beginDate').val();
    endDate= $('#endDate').val();
    billType = $('#billType').val();
    billTitle = $('#billTitle').val();
    houseId = $('#houseId').val();
    billId = $('#billId').val();
    area = $('#area').val();
    unitPrice = $('#unitPrice').val();
    rate = $('#rate').val();
    if (checkMonth()) {
    	$.post(ctx+"/feeBill/saveBill",{
        	houseId:houseId,
        	month:month,
        	money:money,
        	beginDate:beginDate,
        	endDate:endDate,
        	billType:billType,
        	billTitle:billTitle,
        	billId:billId,
        	area:area,
        	unitPrice:unitPrice,
        	rate:rate
    	},function(data){
    		data = JSON.parse(data);
    		if(data.success){
    			layer.msg(data.msg,{
    				icon: 1,
    				time: 2000 //2秒关闭（如果不配置，默认是3秒）
    			},function(){
    				parent.loadContent("/feeBill/gotoDetail?houseId="+houseId);
					parent.layer.close(index);
    			});
    		} else {
    			layer.msg(data.msg,{
    				icon: 2,
    				time: 2000 //2秒关闭（如果不配置，默认是3秒）
    			});
    		}
    	});
    }
    
}

    
    function importBill () {
    	
    	cellId= $('#cellId').val();
    	fileIds = $('#fileIds').val();
    	if (fileIds == null || fileIds == ""){
    		layer.tips('请选择文件', '#fileIds', {
    		    tips: 3
    		});
    		return false;
    	}
    	
        if (checkCell()) {
        	$.ajaxFileUpload({
                url:ctx+"/feeBill/importFeeBill?cellId="+cellId,
                method: 'post',
                type:'post',
                processData: false,  // 告诉jQuery不要去处理发送的数据
                headers: {"Content-Type":  "multipart/form-data; boundary=---------------------------7df2b104b0"},
                /*data: {"cellId":cellId},*/
                secureuri: false, //是否需要安全协议，一般设置为false
                fileElementId: 'fileIds', //文件上传域的ID
                dataType: 'json', //返回值类型 一般设置为json
                success: function (res, status){            //相当于java中try语句块的用法
                	var data= eval("(" + res + ")");
                	if(data.success){
            			layer.msg("导入成功",{
            				icon: 1,
            				time: 2000 //2秒关闭（如果不配置，默认是3秒）
            			},function(){
            				parent.loadContent("/feeBill/infoList");
        					parent.layer.closeAll();
            			});
            		} else {
            			layer.alert(data.msg, function(index){
            				parent.loadContent("/feeBill/infoList");
        					parent.layer.closeAll();
            			});
            		}
                },
                error: function (data, status,e) {           //相当于java中catch语句块的用法
                	layer.msg(data.msg,{
        				icon: 2,
        				time: 2000 //2秒关闭（如果不配置，默认是3秒）
        			},function(){
        				parent.loadContent("/feeBill/infoList");
    					parent.layer.closeAll();
        			});
                }
        		
        	});
        }  
    
}


